package com.erp.erp_ui.Account;

import com.erp.erp_entitys.Account.AccountEntity;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Account.IAccountService;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName AccountControl
 * @Description 帐号相关处理类
 * @Author songjizhen
 * @Date 2020-06-23 11:59
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "account")
 public class AccountControl extends Base {
    @Autowired
    IAccountService accountService;
    @Autowired
    IUserService userService;
    /**
     * 根据用户code、密码登陆
     * @param code
     * @param password
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody

    public R<Map<String,Object>> login(String code, String password){
        String token="";
        try {
            Properties authorize = PropertiesUtils.loadProperties("authorize");
            String privateString =authorize.getProperty("private");
            String publicString=authorize.getProperty("public");
            System.out.println(password);
            //将password解密后得到明文，再用md5加密
            /*password= RSAEncrypt.encrypt("12345678",publicString);
            System.out.println(password);*/
            String pwd= RSAEncrypt.decrypt(password,privateString);
            //将password解密后用MD5加密
            String passwords=DigestUtils.md5DigestAsHex(pwd.getBytes());
            //根据code获取用户user
            UserEntity userEntity = userService.selectUserByCode(code);
            if(userEntity ==null){
                return R.buildError(ResultStatusEnum.ERROR);
            }
            //根据usercode，密码获取帐号
            AccountEntity accountEntity = accountService.selectAccountByCodeandPasswd(code, passwords);
            if(accountEntity ==null){
                return R.buildError(ResultStatusEnum.ERROR);
            }
            //验证帐号是否是授权帐号
            String accountString=authorize.getProperty("account");
            String split=authorize.getProperty("split");
            String[] accounts=accountString.split(split);
            HttpSession session = this.getSession();
            String sessionid = session.getId();

            TokenUtils tu=new TokenUtils();
            token= tu.getToken(sessionid);
            String account="";
            for(int i=0;i<accounts.length;i++){
                //解密获取帐号
                 account= RSAEncrypt.decrypt(accounts[i],privateString);
                //判断帐号code是否是授权帐号
                if(account.equals(accountEntity.getCode())){
                    //将token存入session中
                    session.setAttribute("token", token);
                    //将user存入session中
                    session.setAttribute("user",userEntity);

                    session.setAttribute("yunshupd",accountEntity.getPwd());
                    //将sessionid存入缓存中
                    System.out.println(sessionid);
                    HttpSessionUtils.set(session);
                    //boolean b = this.setBean(sessionid, sessionid);
                    // Object user = this.getBean(sessionid);
                   // Object o = memCachedClient.get(sessionid);
                    break;
                }
            }
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("user",userEntity);
            map.put("token",token);
            map.put("yunshupd",accountEntity.getPwd());
            return R.build(map);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.USER_PWD_ERROR);
        }

    }

    /**
     * 登出
     * @return
     */
    @RequestMapping(value = "logout",method = RequestMethod.POST)
    @ResponseBody
     public R logout(){
        try {
           this.removeSession(this.getSession().getId());
            return R.build("登出成功！");
        }catch (Exception e){
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据员工号,修改密码
     * @param
     * @return
     */
    @RequestMapping(value = "updateAccount",method = RequestMethod.POST)
    @ResponseBody

    public R<Integer> updateAccount(String code,String password,String pwd){
        try {
            Properties authorize = PropertiesUtils.loadProperties("authorize");
            String privateString =authorize.getProperty("private");
            //System.out.println(pwd);
             pwd= RSAEncrypt.decrypt(pwd,privateString);

            AccountEntity accountEntity=new AccountEntity();
            accountEntity.setUsercode(code);
            List<AccountEntity> accountEntities = accountService.selectByExample(accountEntity);
            String accountCode=accountEntities.get(0).getCode();

            accountEntity.setCode(accountCode);


            accountEntity.setPassword(password);
            accountEntity.setPwd(pwd);
            int num = accountService.updateAccount(accountEntity);
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 用户code与帐号code绑定
     * @param usercode
     * @param code
     * @return
     */
    @RequestMapping(value = "updateAccountAndUser",method = RequestMethod.POST)
    @ResponseBody

    public R<Integer> updateAccountAndUser(String usercode,String code,String name){
        try {
            AccountEntity accountEntity=new AccountEntity();
            accountEntity.setUsercode(usercode);
            if(!code.equals("")){
                accountEntity.setCode(code);
            }
            if(!name.equals("")){
                accountEntity.setName(name);
            }

            List<AccountEntity> accountEntities = accountService.selectByExample(accountEntity);
            if (accountEntities.size()>0) {
                AccountEntity accountEntity1 = accountEntities.get(0);
                accountEntity1.setUsercode("");
                accountEntity1.setName("");
                accountService.updateAccount(accountEntity1);
            }
            int num=0;
            if(!code.equals("")){
                 num = accountService.updateAccount(accountEntity);
            }else{
                num=1;
            }

            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据用户usercode获取帐号信息,usercode为空时查询所有的
     * @param usercode
     * @return
     */
    @RequestMapping(value = "getAccountByUserCode",method = RequestMethod.POST)
    @ResponseBody

    public  R<List<AccountEntity>> getAccountByUserCode(String usercode){
        try {
            AccountEntity accountEntity=new AccountEntity();
            accountEntity.setUsercode(usercode);
           List<AccountEntity> accountEntities = accountService.selectByExample(accountEntity);
            for(int i=0;i<accountEntities.size();i++){
                AccountEntity accountEntity1 = accountEntities.get(i);
                accountEntity1.setPassword("");
            }
            return R.build(accountEntities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "getAllAccount")
    @ResponseBody
    public  R<List<AccountEntity>> getAllAccount(){
        try{
            AccountEntity accountEntity=new AccountEntity();
            List<AccountEntity> accountEntities = accountService.selectByExample(accountEntity);
            for(int i=0;i<accountEntities.size();i++){
                AccountEntity accountEntity1 = accountEntities.get(i);
                accountEntity1.setPassword("");
            }
            return R.build(accountEntities);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    public static void main(String[] args)throws Exception {
        Properties authorize = PropertiesUtils.loadProperties("authorize");
        String privateString =authorize.getProperty("private");
        String publicString=authorize.getProperty("public");
        String password= RSAEncrypt.encrypt("87654321",publicString);
            System.out.println(password);
        String pwd= RSAEncrypt.decrypt(password,privateString);
        System.out.println(pwd);
    }
}
